<template>
    <el-card shadow="never" class="aui-card--fill">
      <el-form :inline="true" v-model="SearchForm" clearable  @keydown.enter.native.prevent="getDataList()">
        <el-form-item>
          <el-input v-model="SearchForm.susername" placeholder="提交学生姓名" clearable></el-input>
        </el-form-item>
          <el-form-item>
                <el-select v-model="SearchForm.status" placeholder="审核状态">
                    <el-option label="未审核" value=0></el-option>
                    <el-option label="审核通过" value=2></el-option>
                    <el-option label="已驳回" value=1></el-option>
                    <el-option label="所有文献" value=3></el-option>
                </el-select>
        </el-form-item>
        <el-form-item>
          <el-button @click="getDataList()">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button  type="success" @click="approve()"
              :disabled="dataListSelections.length <= 0">批量通过</el-button>
            <el-button  type="danger" @click="reject()"
              :disabled="dataListSelections.length <= 0">批量驳回</el-button>
        </el-form-item>
      </el-form>
      <el-table :data="dataList" border v-loading="dataListLoading" @selection-change="selectionChangeHandle"
        style="width: 100%;">
        <el-table-column type="selection" header-align="center" align="center" width="50">
          </el-table-column>
        <el-table-column prop="createby" header-align="center" align="center" label="提交学生">
        </el-table-column>
        <el-table-column prop="filename" header-align="center" align="center" label="文献名称" width="160"  show-overflow-tooltip>
        </el-table-column>
        <!-- <el-table-column prop="susername" header-align="center" align="center" width="120" label="学生学号">
        </el-table-column> -->
        <!-- <el-table-column prop="gmtCreate" header-align="center" align="center" width="160" label="创建时间">
        </el-table-column> -->
        
        <el-table-column prop="advise" header-align="center" align="center" width="160" :show-overflow-tooltip="true" label="审核意见">
        </el-table-column>
        <el-table-column prop="status" header-align="center" align="center" label="审核情况">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.status === 0" size="small" type="info">未审核</el-tag>
            <el-tag v-if="scope.row.status === 1" size="small" type="danger">已驳回</el-tag>
            <el-tag v-if="scope.row.status === 2" size="small" type="success">已通过</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="gmtModified" header-align="center" align="center" width="160" label="修改时间">
        </el-table-column>
        <el-table-column fixed="right" header-align="center" align="center" width="260" label="操作">
          <template slot-scope="scope">
            <file-down :pre-view="true" api-url="/teacher/down/wenxian" :file-id="scope.row.id" :FileInfo="scope.row" size="mini"
              icon="" type="text" title="预览"></file-down>
            <file-down api-url="/teacher/down/wenxian" :file-id="scope.row.id" :FileInfo="scope.row" size="mini"
              icon="" type="text" title="下载"></file-down>
              <!-- <el-button type="text" size="small"  icon="el-icon-download" @click="download(scope.row)">下载</el-button> -->
            <el-button type="text" size="small" @click="approve(scope.row.id)">批准通过</el-button>
            <el-button  type="text" size="small" @click="reject(scope.row.id)">驳回修改</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination @size-change="sizeChangeHandle" @current-change="currentChangeHandle" :current-page="pageIndex"
        :page-sizes="[10, 20, 50, 100]" :page-size="pageSize" :total="totalPage"
        layout="total, sizes, prev, pager, next, jumper">
      </el-pagination>
      <add-or-update v-if="addOrUpdateVisible" ref="addOrUpdate" @refreshDataList="getDataList"></add-or-update>
    </el-card>
</template>

<script>
import servicesApi from '@/services/servicesApi';
import debounce from 'lodash/debounce';
import AddOrUpdate from '@/views/Teacher/check-dereport'
import FileDown from '@/components/FileDown.vue';
export default {
  data() {
    return {
      SearchForm: {
        susername: '',
        status: null,
      },
      dataList: [
        { 
         id: '',
         susername: '',
         prospect: '',
         route: '',
         plan: '',
         advise: '', 
         createby: '', 
         repTeacher: '', 
         repTeacher: '', 
         gmtCreate: '', 
         gmtModified: '', 
         status: null
         }
      ],
      pageIndex: 1,
      pageSize: 10,
      totalPage: 0,
      dataListLoading: false,
      dataListSelections: [],
      deleteList: [],
      deleteList: {
                list: []
             },
      addOrUpdateVisible: false, // 新增／更新，弹窗visible状态
    }
  },
  activated() {
    this.getDataList()
  },
  created() {
    this.getDataList()
  },
  components: {
    AddOrUpdate,
    FileDown
},
  methods: {
      //删除
      del(id) {
      let roleIds = id ? [id] : this.dataListSelections.map(item => {
      return item.id
    })
    this.deleteList.list = roleIds
      servicesApi.delTreport(this.deleteList).then(res => {
          // console.log(res.data)
          let code = res.data.code
          if (code === 200) {
              this.$message({
                  message: '删除成功',
                  type: 'success',
                  duration: 1000,
                  onClose: () => {
                      this.getDataList()
                  }
              })
          } else {
              this.$message({
                  message: res.data.msg,
                  type: 'danger',
                  duration: 1000,
                  onClose: () => {
                      this.getDataList()
                  }
              })
          }
      })
  },
  //查看详细信息
      detailed(id) {
      this.addOrUpdateVisible = true
      this.$nextTick(() => {
        // this.$refs.addOrUpdate.dataForm.id = id
        this.$refs['addOrUpdate'].init(id)
      })
    },
    // 获取数据列表
    getDataList: debounce(function() {
      this.dataListLoading = true
      let pageInfo = {
        current: this.pageIndex,
        size: this.pageSize,
        username: this.SearchForm.susername,
        status: this.SearchForm.status === null?3:this.SearchForm.status,
      }
      servicesApi.getTwenx(pageInfo).then(res => {
        // console.log(res.data)
        let code =res.data.code
        let data = res.data.data
        if (code===200) {
          this.dataList = data.list
          this.totalPage = data.total
        } else {
          this.dataList = []
          this.totalPage = 0
        }
        this.dataListLoading = false
      })
    }, 1000, { 'leading': true, 'trailing': false }),
    //下载文件
   download(row) {
            this.percentage = 0;
            this.percentage = 25;
            // console.log(row)
            
            let Form ={
                filename: 'xss攻击与防御总结',
                path: 'student/paper',
                suffix: 'docx'
            }
            let FileName = 'xss攻击与防御总结.docx'
            if (row) {
                Form.filename = row.filename
                Form.path = row.path
                Form.suffix = row.suffix
                FileName = Form.filename + '.' + Form.suffix
            }
            
            //进度条恢复为 0 
            this.percentage = 50;
            //按钮置灰 不可点击
            this.isDisabled = true;
            servicesApi.downloadFiles(Form).then(res => {
                this.percentage = 75;
                // console.log(res)
                //xml返回数据的钩子函数，可以用来获取数据的进度 具体可查看axios的官网
            //     onDownloadProgress: (progressEvent) => {
            //         //progressEvent.loaded 下载文件的当前大小
            //         //progressEvent.total  下载文件的总大小 如果后端没有返回 请让他加上！
            //         let progressBar = Math.round(progressEvent.loaded / progressEvent.total * 100);
            //         //接收进度为99%的时候需要留一点前端编译的时间
            //         if (progressBar >= 99) {
                        this.percentage = 99;
                        this.title = '下载完成，文件正在编译。';
            //         } else {
            //             this.percentage = progressBar;
            //             this.title = '正在下载，请稍等。';
            //         }
            //     }
                try {
                    const blob = new Blob([res.data], {
                        type: 'application/octet-stream'
                    })
                    const downloadElement = document.createElement('a')
                    // 创建下载的链接
                    // 兼容不同浏览器的URL对象
                    const url = window.URL || window.webkitURL || window.moxURL;
                    const href = url.createObjectURL(blob)
                    downloadElement.href = href
                    // 下载后文件名
                    downloadElement.download =  FileName
                    document.body.appendChild(downloadElement)
                    // 点击下载
                    downloadElement.click()
                    // 下载完成移除元素
                    document.body.removeChild(downloadElement)
                    // 释放掉blob对象
                   url.revokeObjectURL(href) 
                    //编译文件完成后，进度条展示为100%100
                    this.percentage = 100;
                    //下载完成 可以重新点击按钮下载
                    this.isDisabled = false;
                } catch (error) {
                    // console.log('下载的文件出错', error)
                }
                
            }).catch(error => {
                // console.log('下载的文件出错', error)
            })
        },
    // 每页数
    sizeChangeHandle(val) {
      this.pageSize = val
      this.pageIndex = 1
      this.getDataList()
    },
    // 当前页
    currentChangeHandle(val) {
      this.pageIndex = val
      this.getDataList()
    },
    // 多选
    selectionChangeHandle(val) {
      this.dataListSelections = val
      // console.log('多选')
      // console.log(this.dataListSelections)
    },
    //批准通过
    approve(id) {
      let userIds = id ? [id] : this.dataListSelections.map(item => {
          return item.id
        })
      // console.log(userIds)
      this.$prompt('请输入通过意见', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      })
      .then(({value}) => {
        // console.log(value)
          this.deleteList = userIds
          let checkList = {
          advise: value,
          list: this.deleteList,
          status: 2
      }
        servicesApi.checkTwenx(checkList).then(res => {
          // console.log(res.data)
          let code = res.data.code
          if (code === 200) {
            this.$message({
              type: 'success',
              message: '批准通过成功',
              duration: 1500,
              onClose: () => {
                this.getDataList()
              }
            })
          } else {
            this.$message.error(res.data.msg)
          }
        })
      }).catch(() => {
            this.$message({
            type: 'warning',
            message: '取消批准通过'
          });  
       })
  },
  //驳回
    reject(id) {
      let userIds = id ? [id] : this.dataListSelections.map(item => {
          return item.id
        })
      // console.log(userIds)
      this.$prompt('请输入驳回意见', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      })
      .then(({value}) => {
        // console.log(value)
          this.deleteList = userIds
          let checkList = {
          advise: value,
          list: this.deleteList,
          status: 1
      }
        servicesApi.checkTwenx(checkList).then(res => {
          // console.log(res.data)
          let code = res.data.code
          if (code === 200) {
            this.$message({
              type: 'success',
              message: '驳回成功',
              duration: 1500,
              onClose: () => {
                this.getDataList()
              }
            })
          } else {
            this.$message.error(res.data.msg)
          }
        })
      }).catch(() => {
            this.$message({
            type: 'info',
            message: '取消驳回'
          });  
       })
  },
  }
}
</script>
